<?php

class CustReserveHead extends AppModel {
    var $name = 'CustReserveHead';

    var $useTable = 'cust_reserve_heads';

    var $displayField = 'reserve_no';

    var $hasMany = array(
            'CustReserve' => array(
                            'foreignKey' => 'cust_reserve_head_id'
            )
    );

    var $belongsTo = array(
            'Supplier', 'SiteCostCenter', 'CustReserveStatus',
            'Customer' => array(
                            'fields' => array('id', 'cust_no', 'name')
            ),
            'Site' => array(
                            'fields' => array('id', 'site_no', 'name')
            ),
            'User' => array(
                            'foreignKey' => 'collector_id',
                            'fields' => array('username', 'name')
            )
    );


    var $validate = array(
            'reserve_no' => array(
                            'notEmpty' => array(
                                            'rule' => array('notEmpty'),
                                            'message' => 'Reserve no. is required.',
                                            'required' => true,
                                            'on' => 'create'
                            ),
                            'isUnique' => array(
                                            'rule' => 'isUnique',
                                            'message' => 'This reserve no. is already taken.',
                                            'on' => 'create'
                            ),
            ),
            'reserve_date' => array(
                            'rule' => array('date', 'dmy'),
                            'message' => 'Reserve date is required.',
                            'required' => true,
                            'on' => 'create'
            ),
            'customer_id' => array(
                            'rule' => 'notEmpty',
                            'message' => 'Customer is required.',
                            'required' => true,
                            'on' => 'create'
            ),
            'site_id' => array(
                            'rule' => 'notEmpty',
                            'message' => 'Site is required.',
                            'required' => true,
                            'on' => 'create'
            ),
            'dispatch_from' => array(
                            'rule' => 'notEmpty',
                            'message' => 'Dispatch from is required.',
                            'required' => true,
                            'on' => 'create'
            ),
            'cust_reserve_status_id' => array(
                            'rule' => 'notEmpty',
                            'message' => 'Reserve status is required.',
                            'required' => true,
                            'on' => 'create'
            ),
    );

    function beforeSave() {

        if (isset($this->data['CustReserveHead']['reserve_date'])) {
            $this->data['CustReserveHead']['reserve_date'] = $this->dateFormatBeforeSave($this->data['CustReserveHead']['reserve_date']);
        }
        return true;
    }

    function afterFind($results) {
        foreach ($results as &$custStockOutHead) {
            if (isset($custStockOutHead['CustReserveHead']['reserve_date'])) {
                $custStockOutHead['CustReserveHead']['reserve_date'] = $this->dateFormatAfterFind($custStockOutHead['CustReserveHead']['reserve_date']);
            }
        }
        return $results;
    }


    /**
     * Custom Query สร้าง Query มาเองให้เป็นรูปแบบที่เหมาะสมสำหรับหน้า print
     * @param int $id cust_reserve_head_id
     * @return array data
     */
    function findForPrintByid($id) {
        $this->contain(array('Customer', 'Site', 'Supplier', 'SiteCostCenter',
                'CustReserve' => array('Product' => array('part_no', 'supplier_part_no', 'text', 'Unit'), 'CustProductSite')
                )
        );
        $data = $this->findById($id);

        $this->CustReserve->bindModel(array(
                'hasMany' => array(
                        'ProductSerial' => array(
                                'foreignKey' => 'cust_reserve_id',
                        )
                )
                )
        );

        $Product = $this->CustReserve->Product;
        $PS = $this->CustReserve->ProductSerial;
        $CL = $PS->CustLocation;

        // วนลูปรายการ CustReserve
        foreach($data['CustReserve'] as &$cr) {
            // หา Location ที่มีอยู่ใน CustReserve รายการนี้
            $psCLs = $PS->find('all', array(
                    'fields' => array('DISTINCT cust_location_id', 'price'),
                    'conditions' => array(
                            'cust_reserve_id' => $cr['id'],
                            'product_id' => $cr['product_id'],
                    ),
                    'contain' => array()
                    )
            );

            // แปะ Location ที่ได้เข้า CustReserve
            foreach ($psCLs as $psCl) {
                $CL->contain();
                $custLocation = $CL->findById($psCl['ProductSerial']['cust_location_id']);

                // option สำหรับ query product serial
                $options = array(
                        'contain' => array(),
                        'conditions' => array(
                                'cust_reserve_id' => $cr['id'],
                                'product_id' => $cr['product_id'],
                                'cust_location_id' => $psCl['ProductSerial']['cust_location_id'],
                                'price' => $psCl['ProductSerial']['price'],
                        )
                );

                // นับจำนวนที่ stock out ใน location นี้
                $ps_count = $PS->find('count', $options);

                // ถึง เฉพาะ Product Serial ที่มี Serial no หรือ other information (ถ้าไม่มีจะออกมา 1 แถว)
                $options['fields'] = array('DISTINCT serial_no', 'other_information');
                $ps = $PS->find('all', $options);

                $custLocation['price'] = $psCl['ProductSerial']['price'];
                $custLocation['reserve_qty'] = $ps_count;
                $custLocation['PS'] = $ps;

                $cr['ProductLocation'][] = $custLocation;
            }
        }
        return $data;
    }

}
?>
